package com.example.myapplication2

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.*
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_android_thread.*
import kotlin.concurrent.thread


class AndroidThreadActivity : AppCompatActivity() {
    val updateText = 1
    lateinit var downloadBinder: MyService.DownloadBinder
//    val handler = object : Handler(Looper.getMaininLooper()) {
//        override fun handleMessage(msg: Message) {
//            // 在这里可以进行UI操作
//            when (msg.what) {
//                updateText -> textView.text = "Nice to meet you"
//            }
//        }
//    }
private val connection = object : ServiceConnection {
    override fun onServiceConnected(name: ComponentName, service: IBinder) {
        downloadBinder = service as MyService.DownloadBinder
        downloadBinder.startDownload()
        downloadBinder.getProgress()
    }
    override fun onServiceDisconnected(name: ComponentName) {
    }
}
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_android_thread)
        startServiceBtn.setOnClickListener {
            val intent = Intent(this, MyService::class.java)
            startService(intent) // 启动Service
        }
        stopServiceBtn.setOnClickListener {
            val intent = Intent(this, MyService::class.java)
            stopService(intent) // 停止Service
        }
        changeTextBtn.setOnClickListener {
            thread {
                val msg = Message()
                msg.what = updateText
                //handler.sendMessage(msg) // 将Message对象发送出去
            }
        }
        bindServiceBtn.setOnClickListener {
            val intent = Intent(this, MyService::class.java)
            bindService(intent, connection, Context.BIND_AUTO_CREATE) // 绑定Service
        }
        unbindServiceBtn.setOnClickListener {
            unbindService(connection) // 解绑Service
        }
        startIntentServiceBtn.setOnClickListener {
            // 打印主线程的id
            Log.d("MainActivity", "Thread id is ${Thread.currentThread().name}")
            val intent = Intent(this, MyIntentService::class.java)
            startService(intent)
        }
    }
}